package com.demo.zhlg.service.impl;

import com.demo.zhlg.mapper.TaskOrdersMapper;
import com.demo.zhlg.util.Result;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.demo.zhlg.entity.Ratings;
import com.demo.zhlg.mapper.RatingsMapper;
import com.demo.zhlg.service.RatingsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.sqlite.date.DateFormatUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static com.demo.zhlg.entity.table.RatingsTableDef.RATINGS;
import static com.demo.zhlg.entity.table.TaskOrdersTableDef.TASK_ORDERS;
import static com.mybatisflex.core.query.QueryMethods.avg;
import static com.mybatisflex.core.query.QueryMethods.user;
import static java.lang.Double.sum;

/**
 *  服务层实现。
 *
 * @author lenovo
 * @since 2025-04-26
 */
@Service
public class RatingsServiceImpl extends ServiceImpl<RatingsMapper, Ratings> implements RatingsService {

    @Autowired
    private RatingsMapper ratingsMapper;

    @Autowired
    private TaskOrdersMapper taskOrdersMapper;

    private int getUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        return loginUser.getUser().getUserId();
    }

    @Override
    public Object submitRating(Ratings rating) {
        rating.setCreateTime(DateFormatUtils.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
        rating.setUpdateTime(DateFormatUtils.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
        return Result.success(ratingsMapper.insert(rating));
    }

    @Override
    public Object getUserRatingStats(Integer userId) {
        Map<String, Object> res = new HashMap<>();

        // 查询该用户收到的评价总数
        int totalRatings = (int)ratingsMapper.selectCountByQuery(
                new QueryWrapper()
                        .where(RATINGS.TO_USER_ID.eq(userId))
        );

        // 如果没有评价记录，返回默认值
        if (totalRatings == 0) {
            res.put("overallRating", 0.0);
            res.put("completedTaskCount", 0);
            res.put("goodRatingRate", 0);
            res.put("totalRatings", 0);
            res.put("serviceQualityAverage", 0.0);
            res.put("responseSpeedAverage", 0.0);
            res.put("communicationAttitudeAverage", 0.0);
            return Result.success(res);
        }

        // 查询平均综合评分
        Double overallRating = (Double)ratingsMapper.selectObjectByQuery(
                new QueryWrapper()
                        .select(avg(RATINGS.OVERALL_RATING).as("avg_rating"))
                        .where(RATINGS.TO_USER_ID.eq(userId))
        );

        // 查询服务质量平均分
        Double serviceQualityAvg = (Double)ratingsMapper.selectObjectByQuery(
                new QueryWrapper()
                        .select(avg(RATINGS.SERVICE_QUALITY).as("avg_service"))
                        .where(RATINGS.TO_USER_ID.eq(userId))
        );

        // 查询响应速度平均分
        Double responseSpeedAvg = (Double)ratingsMapper.selectObjectByQuery(
                new QueryWrapper()
                        .select(avg(RATINGS.RESPONSE_SPEED).as("avg_response"))
                        .where(RATINGS.TO_USER_ID.eq(userId))
        );

        // 查询沟通态度平均分
        Double communicationAttitudeAvg = (Double)ratingsMapper.selectObjectByQuery(
                new QueryWrapper()
                        .select(avg(RATINGS.COMMUNICATION_ATTITUDE).as("avg_communication"))
                        .where(RATINGS.TO_USER_ID.eq(userId))
        );

        // 查询好评数量（评分>=4的评价）
        int goodRatingsCount = (int)ratingsMapper.selectCountByQuery(
                new QueryWrapper()
                        .where(RATINGS.TO_USER_ID.eq(userId))
                        .and(RATINGS.OVERALL_RATING.ge(4.0))
        );

        // 计算好评率
        int goodRatingRate = totalRatings > 0 ? (int)((goodRatingsCount * 100.0) / totalRatings) : 0;

        // 查询用户完成的任务数
        int completedTaskCount = (int)taskOrdersMapper.selectCountByQuery(
                new QueryWrapper()
                        .where(TASK_ORDERS.WORKER_ID.eq(userId))
                        .or(TASK_ORDERS.EMPLOYER_ID.eq(userId))
                        .and(TASK_ORDERS.ORDER_STATUS.eq(2)) // 假设状态2表示已完成
        );

        // 组装结果
        res.put("overallRating", overallRating != null ? overallRating : 0.0);
        res.put("completedTaskCount", completedTaskCount);
        res.put("goodRatingRate", goodRatingRate);
        res.put("totalRatings", totalRatings);
        res.put("serviceQualityAverage", serviceQualityAvg != null ? serviceQualityAvg : 0.0);
        res.put("responseSpeedAverage", responseSpeedAvg != null ? responseSpeedAvg : 0.0);
        res.put("communicationAttitudeAverage", communicationAttitudeAvg != null ? communicationAttitudeAvg : 0.0);

        return Result.success(res);
    }

    @Override
    public Object getRatingsTo() {
        return Result.success(ratingsMapper.selectListByQuery(
                new QueryWrapper()
                        .where(RATINGS.TO_USER_ID.eq(getUserId()))
                        .orderBy(RATINGS.ORDER_ID, false)
        ));
    }

    @Override
    public Object getRatingsFrom() {
        return Result.success(ratingsMapper.selectListByQuery(
                new QueryWrapper()
                        .where(RATINGS.FROM_USER_ID.eq(getUserId()))
                        .orderBy(RATINGS.ORDER_ID, false)
        ));
    }
}
